package com.eightbears.beboy.ui.login;

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.eightbears.beboy.R;
import com.eightbears.beboy.SplashActivity;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.util.CommonAPI;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.builder.PutFormBuilder;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.entity.status.Status_Error;
import com.pnikosis.materialishprogress.ProgressWheel;
import com.socks.library.KLog;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.ui.user.activity.TransferActivity.PARAMS_PAY_TRANSFER;

public class ForgetActivity extends BaseActivity {

    private int millisInFuture = 30000;
    private int countDownInterval = 1000;

    @BindView(R.id.btn_get_code)
    TextView btn_get_code;
    @BindView(R.id.et_forger_code)
    EditText et_forger_code;
    @BindView(R.id.et_phone_num)
    EditText et_phone_num;
    @BindView(R.id.progress_wheel)
    ProgressWheel progress_wheel;
    @BindView(R.id.et_new_pass)
    EditText et_new_pass;
    @BindView(R.id.et_agree_new_pass)
    EditText et_agree_new_pass;
    @BindView(R.id.btn_forger_ensure)
    Button btn_forger_ensure;
    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;
    @BindView(R.id.tv_title)
    TextView tv_title;


    private String url;
    private String securityCode;
    private String phoneNum;
    private String pass;
    private String newPass;
    private String mTransfer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        mTransfer = getIntent().getStringExtra(PARAMS_PAY_TRANSFER);
        if (!TextUtils.isEmpty(mTransfer)) {//区分URL支付密码URL和密码URL
            tv_title.setText(R.string.text_forget_set_pass);
            et_new_pass.setInputType(InputType.TYPE_CLASS_NUMBER);
            et_new_pass.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)}); //最大输入长度
            et_new_pass.setTransformationMethod(PasswordTransformationMethod.getInstance()); //设置为密码输入框
            et_agree_new_pass.setInputType(InputType.TYPE_CLASS_NUMBER);
            et_agree_new_pass.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)}); //最大输入长度
            et_agree_new_pass.setTransformationMethod(PasswordTransformationMethod.getInstance()); //设置为密码输入框
            et_new_pass.setHint(R.string.hint_input_new_pay_pass);
            et_agree_new_pass.setHint(R.string.hint_confirm_new_pay_pass);
        } else {
            tv_title.setText(R.string.text_forget_pass);
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initEvent() {
        et_phone_num.addTextChangedListener(watcher);
        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
    }

    @OnClick(R.id.btn_get_code)
    void getCode() {
        if (!validPhoneNum()) {
            return;
        }
        progress_wheel.setVisibility(View.VISIBLE);
        replaceButtonUnable();
        eventButtonUnable();
        timer.start();
        getNetCodeData();
    }

    @OnClick(R.id.btn_forger_ensure)
    void submit() {
        if (validCheckInput()) {
            progress_wheel.setVisibility(View.VISIBLE);
            replaceLoginUnable();
            updatePass();
        }
    }

    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }

    /**
     * 获取网络信息请求验证码接口
     */
    private void getNetCodeData() {
        //请求网络
        OkHttpUtils.post().url(CommonAPI.URL_VERIFICATION_CODE)
                .addParams("mobile", phoneNum)//请求带上11位手机号码
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                progress_wheel.setVisibility(View.GONE);
                ShowToast.showShortToast(R.string.alert_code_send_success);
            }

            @Override
            public void onError(Call call, Exception e) {
                progress_wheel.setVisibility(View.GONE);
                timer.cancel();
                replaceButtonClickable();
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(ForgetActivity.this, status_error);
            }
        });
    }

    private void updatePass() {
        PutFormBuilder builder = OkHttpUtils.put();
        if (!TextUtils.isEmpty(mTransfer)) {//区分URL支付密码URL和密码URL
            url = CommonAPI.URL_RESET_PAY_CODE;
            builder.url(url);
            builder.addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken());
            builder.addParams("mobile", phoneNum);//手机号码
            builder.addParams("code", securityCode);//手机验证号码
            builder.addParams("password", pass);//密码
            builder.addParams("re_password", newPass);//重复密码
        } else {
            url = CommonAPI.URL_RESET_CODE;
            builder.url(url);
            builder.addParams("mobile", phoneNum);//手机号码
            builder.addParams("code", securityCode);//手机验证号码
            builder.addParams("password", pass);//密码
            builder.addParams("re_password", newPass);//重复密码
        }

        KLog.e(url);
        builder.build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                url = "";
                KLog.e(response);
                progress_wheel.setVisibility(View.GONE);
                if (!TextUtils.isEmpty(mTransfer)) {
                    KLog.e("修改支付密码成功");
                    ShowToast.showShortToast(getString(R.string.text_repass_pay_success));
                    finish();
                } else {
                    ShowToast.showShortToast(getString(R.string.text_repass_success));
                    finish();
//                    startLocalActivityAndClear((Activity) mContext, SplashActivity.class);
//                    SPUtil.clear();
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                progress_wheel.setVisibility(View.GONE);
                replaceLoginClickable();
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError((Activity) mContext, status_error);
            }
        });
    }

    private boolean validCheckInput() {
        pass = et_new_pass.getText().toString().trim();
        newPass = et_agree_new_pass.getText().toString().trim();

        if (!isNetWorkConnected(this)) {
            return false;
        }

        if (pass.contains(".")) {
            ShowToast.showShortToast(getString(R.string.alert_please_input_new_pass_pot));
            return false;
        }

        if (TextUtils.isEmpty(pass)) {
            ShowToast.showShortToast(getString(R.string.alert_please_input_new_pass));
            return false;
        }

        if (TextUtils.isEmpty(newPass)) {
            ShowToast.showShortToast(getString(R.string.alert_please_input_pass_again));
            return false;
        }

        if (pass.length() < 6) {
            ShowToast.showShortToast(getString(R.string.alert_pass_lenght));
            return false;
        }

        if (!pass.equals(newPass)) {
            ShowToast.showShortToast(getString(R.string.alert_pass_inconformity));
            return false;
        }

        if (!validPhoneNum() || !validSecurityCode()) {
            return false;
        }

        return true;
    }

    private boolean validSecurityCode() {
        securityCode = et_forger_code.getText().toString().trim();
        if (securityCode.length() != 4) {
            ShowToast.showShortToast(R.string.error_security_code);
            return false;
        }
        return true;
    }

    private boolean validPhoneNum() {
        phoneNum = et_phone_num.getText().toString().trim();
        if (!CommonUtils.isPhoneNum(phoneNum)) {
            ShowToast.showShortToast(R.string.error_phone_num_input);
            return false;
        }
        return true;
    }


    CountDownTimer timer = new CountDownTimer(millisInFuture, countDownInterval) {
        @Override
        public void onTick(long millisUntilFinished) {

            btn_get_code.setText(millisUntilFinished / countDownInterval + getString(R.string.alert_code_count_down));
        }

        @Override
        public void onFinish() {
            replaceButtonClickable();
        }
    };

    private final TextWatcher watcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() == 11) {
                replaceButtonClickable();
            } else {
                replaceButtonUnable();
            }
        }
    };

    private void replaceButtonClickable() {
        btn_get_code.setTextColor(getResources().getColor(R.color.text_color_fff));
        btn_get_code.setText(getText(R.string.text_get_security_code));
        btn_get_code.setBackgroundDrawable(getResources().getDrawable(R.drawable.background_circle_bead_blue_style));
        btn_get_code.setFocusable(true);
        btn_get_code.setClickable(true);
    }

    private void replaceButtonUnable() {
        btn_get_code.setTextColor(getResources().getColor(R.color.text_color_fff));
        btn_get_code.setBackgroundDrawable(getResources().getDrawable(R.drawable.background_gray_unable));
    }

    private void eventButtonUnable() {
        btn_get_code.setFocusable(false);
        btn_get_code.setClickable(false);
    }


    private void replaceLoginClickable() {
        btn_forger_ensure.setTextColor(getResources().getColor(R.color.text_color_fff));
        btn_forger_ensure.setText(getText(R.string.text_submit));
        btn_forger_ensure.setBackgroundDrawable(getResources().getDrawable(R.drawable.background_circle_bead_blue_style));
        btn_forger_ensure.setFocusable(true);
        btn_forger_ensure.setClickable(true);
    }

    private void replaceLoginUnable() {
        btn_forger_ensure.setTextColor(getResources().getColor(R.color.text_other_info_color));
        btn_forger_ensure.setText(R.string.alert_submiting);
        btn_forger_ensure.setBackgroundDrawable(getResources().getDrawable(R.drawable.background_gray_unable));
        btn_forger_ensure.setFocusable(false);
        btn_forger_ensure.setClickable(false);
    }
}
